package com.lipiao.traveltreasure.controller.travelTreasure;

import com.lipiao.traveltreasure.bean.travelTreasureBean.BaseUserBean;
import com.lipiao.traveltreasure.service.travelTreasure.AllUserService;
import com.lipiao.traveltreasure.util.UploadFileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 控制器-车行宝
 * 所有用户通用的接口 /travelTreasureApi/user
 * 使用String userKind区分不同种类的用户
 * 1.登录
 * 2.注册
 * 3.修改密码
 * 4.上传头像图片
 * 5.完善个人信息(空添加，非空修改)
 * 6.登出账号
 * 7.通过userId查找 返回对应的用户数据Bean
 */
@Api(tags = "车行宝-所有用户通用接口")
@Controller
@RequestMapping("/travelTreasureApi/user")
public class AllUserController {
    private String TAG = "ActivityController";
    //注入业务对象
    @Resource
    private AllUserService allUserService;
    //存储预返回页面的结果对象
    private Map<String, Object> result;
    //头像存储位置
    //项目下存储头像的目录,需放在静态资源'static'目录下
    private final String uploadPath = "/static/upload/userPicture";

    /**
     * @param username 账号
     * @param password 密码
     * @param userKind 用户类型
     * @return 返回登录请求json数据
     * @description: 1.通用登录
     */
    @ApiOperation("通用登录")
    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(String username, String password, int userKind) {
        //防止返回信息重复
        result = new HashMap<>();
        try {
            //查询用户userId前，判断账号和密码是否正确
            BaseUserBean baseUserBean = allUserService.findById(username);
            //将strUserId返回给前端
            //异常：1.没有此账号
            if (baseUserBean == null) {
                result.put("strUserId", "null");
                result.put("message", "loginError:没有此账号");
            } else {
                //异常 2.密码不正确
                if (baseUserBean.getPassword().equals(password)) {
                    String strUserId = allUserService.login(username, password, userKind);
                    result.put("strUserId", strUserId);
                    result.put("message", "loginSuccess");
                } else {
                    result.put("strUserId", "null");
                    result.put("message", "loginError:密码错误");
                }
            }
        } catch (Exception e) {
            result.put("strUserId", "null");
            result.put("message", "loginError");
            e.printStackTrace();
        } finally {
            return result;
        }
    }


    /**
     * @param username 账号
     * @param password 密码
     * @param userKind 用户类型
     * @return register结果
     * @description: 2.通用注册
     */
    @ApiOperation("通用注册")
    @PostMapping("/register")
    @ResponseBody
    public Map<String, Object> register(String username, String password, int userKind) {
        //防止返回信息重复
        result = new HashMap<>();
        try {
            //在将注册信息添加到对应的用户表之前，判断账号是否存在 username主键唯一
            BaseUserBean baseUserBean = allUserService.findById(username);
            //如果为空值 说明可以注册此用户
            if (baseUserBean == null) {
                String userId = UUID.randomUUID() + "";//使用UUID随机生成一个userId
                allUserService.register(username, password, userKind, userId);
                result.put("message", "registerSuccess");
            } else {
                result.put("message", "registerError:该账号已注册");
            }
        } catch (Exception e) {
            result.put("message", "registerError");
            e.printStackTrace();
        } finally {
            return result;
        }
    }

    /**
     * @param username    账号
     * @param password    密码
     * @param newPassword 新密码
     * @param userKind    用户类型
     * @return changePassword结果
     * @description: 3.通用修改密码
     */
    @ApiOperation("通用修改密码")
    @PostMapping("/changePassword")
    @ResponseBody
    public Map<String, Object> changePassword(String username, String password, String newPassword, int userKind) {
        //防止返回信息重复
        result = new HashMap<>();
        try {
            //在将修改密码前 判断密码是否匹配旧密码
            BaseUserBean baseUserBean = allUserService.findById(username);
            if (baseUserBean.getPassword().equals(password)) {
                allUserService.changePassword(username, password, newPassword, userKind);
                result.put("message", "changePasswordSuccess");
            } else {
                result.put("message", "changePasswordError:原始密码不正确");
            }
        } catch (Exception e) {
            result.put("message", "changePasswordError");
        } finally {
            return result;
        }

    }

    /**
     * @description: 4.上传头像图片
     * -原理:将头像上传到项目发布目录中,通过读取数据库中的头像路径来显示头像
     * @param: photo ax
     * @param: request
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * /travelTreasureApi/activity/uploadPhoto
     */
    @ApiOperation("通用上传头像")
    @PostMapping("/uploadUserPhoto")
    @ResponseBody
    public Map<String, Object> uploadPhoto(MultipartFile userPhoto) throws FileNotFoundException, UnsupportedEncodingException {
        //指定存储头像目录的完整路径(项目发布路径): 若不使用绝对路径,则Spring boot会默认将上传的文件存储到临时目录中
        String dirPath = URLDecoder.decode(ResourceUtils.getURL("classpath:").getPath(), StandardCharsets.UTF_8.name()) + uploadPath;//加.name()
        //返回头像的上传结果
        return UploadFileUtil.getUploadResult(userPhoto, dirPath, uploadPath);
    }

    /**
     * @description: 5.完善个人信息(空添加 ， 非空修改)
     */
    @ApiOperation("通用更新用户信息")
    @PostMapping("/updateUserInformation")
    @ResponseBody
    public Map<String, Object> updateUserInformation(String username, String password, String newPassword, int userKind) {
        //防止返回信息重复
        result = new HashMap<>();
        try {
            allUserService.updateUserInformation();//登出


        } catch (Exception e) {
            result.put("message", "changePasswordError");
        } finally {
            return result;
        }

    }

    /**
     * @description: 6.登出账号
     */
    @ApiOperation("通用登出")
    @PostMapping("/loginOut")
    @ResponseBody
    public Map<String, Object> loginOut(String username, String password, String newPassword, int userKind) {
        //防止返回信息重复
        result = new HashMap<>();
        try {
            allUserService.loginOut();//登出

        } catch (Exception e) {
            result.put("message", "loginOutError");
        } finally {
            return result;
        }

    }


}
